package com.qf.web.servlet;

import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 2020/12/9 9:55
 *
 * @author：Lixubiao
 */

/**
 * 公共Servlet，需要用到自己继承
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            String methodName = req.getParameter("method");
            Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            String url=(String)method.invoke(this, req,resp);
            if (!StringUtils.isEmpty(url)){
                //重定向前加：redirect：
                if (url.startsWith("redirect:")){
                    resp.sendRedirect(url.split("redirect:")[1]);
                }else {
                    req.getRequestDispatcher(url).forward(req, resp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
